package com.tiance.demo.ui.menu;

import com.tiance.demo.observer.ObserverData;
import com.tiance.demo.observer.ObserverEvent;
import com.tiance.demo.observer.ObserverSystem;
import com.tiance.demo.service.mysql.analyzer.PageAnalyzer;
import com.tiance.demo.service.mysql.bo.Page;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.MenuItem;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class Menuitem_Open extends MenuItem implements EventHandler {

    public Menuitem_Open() {
        this.setText("Open ibd");

        this.setOnAction(this);

    }

    @Override
    public void handle(Event event) {
        FileChooser fc = new FileChooser();
        fc.setTitle("Please Choose ibd File");
        fc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("MySQL Data File", "*"));
        Stage fs = new Stage();
        File file = fc.showOpenDialog(fs);

        if (file == null) {
            return;
        }

        byte[] ibdBytes = new byte[(int) file.length()];
        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(ibdBytes);
            List<byte[]> pageBytes = splitIntoPage(ibdBytes);

            List<Page> pages = analysePage(pageBytes);

            ObserverSystem.notifyObservers(ObserverEvent.OPEN_FILE, new ObserverData(pages));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<byte[]> splitIntoPage(byte[] bytes) {
        List<byte[]> list = new ArrayList<>();

        int offset = 0;
        while (bytes.length > offset) {
            byte[] pageBytes = new byte[Page.SIZE];
            System.arraycopy(bytes, offset, pageBytes, 0, Page.SIZE);
            offset = offset + Page.SIZE;
            list.add(pageBytes);
        }

        return list;
    }

    private static List<Page> analysePage(List<byte[]> pageBytes) {
        List<Page> pages = new ArrayList<>(pageBytes.size());
        for (byte[] pageByte : pageBytes) {
            Page page = PageAnalyzer.analyse(pageByte);
            pages.add(page);
        }

        return pages;
    }
}
